import numpy as np
import matplotlib.pyplot as plt
from dataset import get_satellite
def analyze_class_balance(y, *, pos_label=1, out_png='class_pie.png'):
    """
    Parameters
    ----------
    y         : 1-D array-like, 标签向量 (+1 / -1)
    pos_label : 哪个数字算“正类”（默认 +1）
    out_png   : 饼图保存路径
    """
    y = np.asarray(y).ravel()

    pos_cnt = np.sum(y ==  pos_label)
    neg_cnt = np.sum(y != pos_label)
    total   = len(y)

    print(f'正类 (+{pos_label}) : {pos_cnt}  ({pos_cnt/total:.2%})')
    print(f'负类 (others)  : {neg_cnt}  ({neg_cnt/total:.2%})\n')

    # ---- 画饼图 ----
    labels = [f'Positive\n{pos_cnt} ({pos_cnt/total:.1%})',
              f'Negative\n{neg_cnt} ({neg_cnt/total:.1%})']
    sizes  = [pos_cnt, neg_cnt]
    explode = (0.03, 0)            # 正类凸出一点点

    fig, ax = plt.subplots(figsize=(4,4))
    ax.pie(sizes, labels=labels, explode=explode,
           autopct='%1.1f%%', startangle=90,
           colors=['#66c2a5', '#8da0cb'])
    ax.set_title('Class Distribution')
    ax.axis('equal')

    plt.tight_layout()
    fig.savefig(out_png, dpi=150)
    print(f'✅  饼图已保存为 {out_png}')
    plt.close(fig)
    return {'positive': pos_cnt, 'negative': neg_cnt}, fig
if __name__ == '__main__':
    Lx, Ly, Ux, Uy = get_satellite()
    stats, _ = analyze_class_balance(Uy, pos_label=1)